<!-- src/components/MusicPackageView.vue -->
<template>
  <v-app>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-card>
  <v-card-title>
    音乐包管理
    <v-spacer></v-spacer>
    <v-btn color="primary" @click="openDialog()">
      添加音乐包
    </v-btn>
  </v-card-title>
  <v-card-text>
    <v-text-field
      v-model="search"
      label="搜索音乐包"
      class="mb-4"
      clearable
    ></v-text-field>
    <v-data-table
      :headers="headers"
      :items="music_packages"
      :loading="loading"
      :search="search"
      class="elevation-1"
    >
      <template v-slot:item.actions="{ item }">
        <v-icon small @click="deleteItem(item)">
          mdi-delete
        </v-icon>
      </template>
    </v-data-table>
  </v-card-text>
</v-card>
        </v-col>
      </v-row>

      <!-- 编辑对话框 -->
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span>{{ formTitle }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="editedItem.name"
                    label="音乐包名称"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-textarea
                      label="音乐包描述"
                      variant="outlined"
                      v-model="editedItem.description"
                      auto-grow
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">保存</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- 删除确认对话框 -->
      <v-dialog v-model="dialogDelete" max-width="500px">
        <v-card>
          <v-card-title>确认删除</v-card-title>
          <v-card-text>确定要删除这条音乐记录吗？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
            <v-btn color="blue darken-1" text @click="deleteItemConfirm">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </v-app>
</template>

<script>
const API_BASE = import.meta.env.VITE_API_BASE || 'http://106.75.215.61:3000';

export default {
  name: 'MusicPackageView',
  data: () => ({
    apiBase: API_BASE,
    dialog: false,
    dialogDelete: false,
    loading: false,
    search: '', // 搜索关键词
    // ✅ 改为 Vuetify 3 的写法：title + key
    headers: [
      { title: '音乐ID', key: 'id' },
      { title: '音乐包名称', key: 'name' },
      { title: '音乐包详情', key: 'description' },
      { title: '操作', key: 'actions', sortable: false }
    ],
    music_packages: [],
    editedIndex: -1,
    editedItem: {
      id: '',
      name: '',
      description: ''
    },
    defaultItem: {
      id: '',
      name: '',
      description: ''
    }
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? '新增音乐' : '编辑音乐'
    },
  },

  methods: {
    async getAllMusicPackages() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/getAllMusicPackages`)
        this.music_packages = res.data
      } catch (e) {
        this.$toast?.error('获取音乐包列表失败')
      } finally {
        this.loading = false
      }
    },

    async deleteMusicPackage(id) {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/deleteMusicPackage/` + id)
        if (res.status === 200) {
          this.$toast?.success('删除成功')
        } else {
          throw new Error('删除失败')
        }
      } catch (e) {
        this.$toast?.error('删除失败')
      } finally {
        this.loading = false
      }
    },

    openDialog() {
      this.editedIndex = -1
      this.editedItem = Object.assign({}, this.defaultItem)
      this.dialog = true
    },

    deleteItem(item) {
      this.editedIndex = this.music_packages.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialogDelete = true
    },

    close() {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    closeDelete() {
      this.dialogDelete = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    async save() {
      if (!this.editedItem.name || !this.editedItem.description) {
        this.$toast?.error('请填写名称并选择文件')
        return
      }

      if (this.editedIndex > -1) {
        Object.assign(this.music_packages[this.editedIndex], this.editedItem)
      } else {
        // const formData = new FormData()
        // formData.append('name', this.editedItem.name)
        // formData.append('description', this.editedItem.description)
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/addMusicPackage`, {
            name: this.editedItem.name,
            description: this.editedItem.description,
          })
          // const response = await this.$axios.post(`${this.apiBase}/addMusicPackage`, formData, {
          //   headers: { 'Content-Type': 'multipart/form-data' }
          // })
          // if (response.status !== 200) throw new Error('上传失败')
          const { id, name, description } = response.data.data
          Object.assign(this.editedItem, { id, name, description })
          this.$toast?.success('创建成功')

          this.music_packages.push({ ...this.editedItem })
          this.close()
        } catch (e) {
          this.$toast?.error('上传失败')
        } finally {
          this.loading = false
        }
      }

      this.close()
    },

    async deleteItemConfirm() {
      await this.deleteMusicPackage(this.editedItem.id)
      this.music_packages.splice(this.editedIndex, 1)
      this.closeDelete()
    }
  },

  mounted() {
    this.getAllMusicPackages()
  }
}
</script>
